package gengine.serverside;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import gengine.common.misc.BaseApplication;
import gengine.common.misc.LogCategory;
import gengine.common.packets.MessagePacket;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;

/**
 * User: arseniy
 * Date: 24.12.11
 */
public class ServerApplication extends BaseApplication {

    ServerThread serverThread;

    public ServerApplication() {
        super();
        packetFactory = new ServerPacketFactory();
    }

    @Override
    public void run() {
        super.run();
        int port = 18600;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder db = dbf.newDocumentBuilder();
            dbf.setIgnoringElementContentWhitespace(true);
            Document document = db.parse("server.xml");
            String val = document.getDocumentElement().getAttribute("port");

            port = Integer.parseInt(val);
        } catch (ParserConfigurationException e) {
            logInstance("server.xml parsing error", LogCategory.Error);
            e.printStackTrace();
            quit();
            return;
        } catch (SAXException e) {
            logInstance("server.xml parsing error", LogCategory.Error);
            e.printStackTrace();
            quit();
            return;
        } catch (IOException e) {
            logInstance("server.xml not found", LogCategory.Error);
            e.printStackTrace();
            quit();
            return;
        }
        serverThread = new ServerThread(this, port);
        serverThread.start();
        while (serverThread.isAlive()) {
            try {
                Thread.sleep(15000);
            } catch (InterruptedException e) {
                e.printStackTrace();
                serverThread.interrupt();
                return;
            }
        }
    }

    @Override
    public void quit() {
        serverThread.interrupt();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        super.quit();
        System.exit(0);
    }
}
